package com.ecarx.library_base.base_util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class AppUtil {


    /**
     * 执行成功
     */
    public static final int CODE_SUCCESS = 0;
    /**
     * 执行异常，在执行命令过程中，有Exception抛出。
     */
    public static final int CODE_ERROR = -1;
    /**
     * 指令执行失败
     */
    public static final int CODE_FAILURE = 1;
    private static final String TAG = "AppUtil";

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 执行shell指令
     *
     * @param command
     * @return
     */
    public static int runShellCommand(String command) {
        Log.d(TAG, "runShellCommand: command=" + command);
        BufferedReader genericReader = null;
        BufferedReader errorReader = null;
        try {
            Process process = Runtime.getRuntime().exec(command);
            errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = null;
            StringBuilder errorLog = new StringBuilder();
            while ((line = errorReader.readLine()) != null) {
                errorLog.append(line).append("\n");
            }
            Log.d(TAG, "error message: " + errorLog.toString());
            genericReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder generic = new StringBuilder();
            while ((line = genericReader.readLine()) != null) {
                generic.append(line).append("\n");
            }
            Log.d(TAG, "generic message: " + generic.toString());
            int exitVal = process.waitFor(); //0 is success,otherwise failure.
            process.destroy();
            Log.d(TAG, "adb process exit value : " + exitVal);
            if (genericReader != null) {
                genericReader.close();
            }

            if (errorReader != null) {
                errorReader.close();
            }
            return exitVal;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return CODE_ERROR;
    }

}
